package com.xul.controller;

import com.xul.entity.User;
import com.xul.entity.User;
import com.xul.service.UserService;
import com.xul.service.UserService;
import com.xul.utils.MD5Utils;
import com.xul.utils.MapController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author xul
 * @create 2021-06-02 23:06
 */

@Controller
@RequestMapping("user")
public class UserController {

    private final String LIST = "user/list";
    private final String ADD = "user/add";
    private final String UPDATE = "user/update";

    @Autowired
    private UserService userService;

    @GetMapping("add")
    public String add() {
        return ADD;
    }

    @PostMapping("create")
    @ResponseBody
    public Map<String, Object> create(User user) {
        user.setUserPwd(MD5Utils.getMD5(user.getUserPwd()));
        int result = userService.create(user);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("delete/{id}")
    @ResponseBody
    public Map<String, Object> delete(@PathVariable("id") Integer id) {
        int result = userService.delete(id);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("delete")
    @ResponseBody
    public Map<String, Object> delete(String ids) {
        int result = userService.delete(ids);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @PostMapping("update")
    @ResponseBody
    public Map<String, Object> update(@RequestBody User user) {
        int result = userService.update(user);
        if (result <= 0) {
            return MapController.getInstance().error().getMap();
        }
        return MapController.getInstance().success().getMap();
    }

    @GetMapping("detail/{id}")
    public String detail(@PathVariable("id") Integer id, ModelMap modelMap) {
        User user = userService.detail(id);
        modelMap.addAttribute("user", user);
        return UPDATE;
    }


    @PostMapping("query")
    @ResponseBody
    public Map<String, Object> query(@RequestBody User user) {
        List<User> list = userService.query(user);
        Integer count = userService.count(user);
        return MapController.getInstance().success().put("data", list).put("count", count).getMap();
    }

    @GetMapping("list")
    public String list() {
        return LIST;
    }


}
